<template>
  <a-modal :title="isEdit ? '编辑' : '新增'" :width="700" :visible="visible" @ok="handleModalConfirm"
    @cancel="handleModalCancel" :confirm-loading="modalLoading">
    <a-form-model ref="form" :model="form" :rules="formRules" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
      <a-form-model-item label="机构名称" prop="institutionName">
        <a-input v-model="form.institutionName" placeholder="请输入" allowClear />
      </a-form-model-item>
      <a-form-model-item label="机构展示名称" prop="institutionShowName">
        <a-input v-model="form.institutionShowName" placeholder="请输入" allowClear />
      </a-form-model-item>
      <a-form-model-item v-if="!isEdit" label="剩余曝光数" prop="coin">
        <a-input-number v-model="form.coin" :min="0" placeholder="请输入" style="width: 100%" />
      </a-form-model-item>
      <a-form-model-item label="图标">
        <a-upload name="file" :action="uploadUrl" accept="image/*" :file-list="fileList" :headers="{ Authorization }"
          list-type="picture-card" @change="handleChange" @preview="handlePreview">
          <a-icon v-if="fileList.length < 1" type="plus" />
          <div v-if="fileList.length < 1" class="ant-upload-text">请选择图片</div>
        </a-upload>
      </a-form-model-item>
      <a-form-model-item label="负责人通知" required>
        <a-switch v-model="form.leadNotice" checked-children="开启" un-checked-children="关闭" style="width:100px" />
      </a-form-model-item>
      <a-form-model-item label="负责人手机号" prop="phoneNumber">
        <a-input v-model="form.phoneNumber" placeholder="请输入" allowClear />
      </a-form-model-item>
    </a-form-model>
    <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
      <img style="width: 100%" :src="previewImage" />
    </a-modal>
  </a-modal>
</template>

<script>
import * as Ajax from '@/api/institution';
import config from '@/utils/config';
export default {
  props: {
    visible: {
      type: Boolean,
    },
    default: {
      type: Object,
      default: () => { },
    },
  },
  data() {
    return {
      modalLoading: false,
      form: {
        institutionName: '',
        institutionShowName: '',
        coin: '',
        leadNotice: false,
        phoneNumber: '',
      },
      formRules: {
        institutionName: { required: true, message: '请输入机构名称', trigger: ['blur', 'change'] },
        institutionShowName: { required: true, message: '请输入机构展示名称', trigger: ['blur', 'change'] },
        coin: { required: true, message: '请输入剩余曝光数', trigger: ['blur', 'change'] },
        phoneNumber: { required: true, message: '请输入负责人手机号', trigger: ['blur', 'change'] },
      },
      fileList: [],
      Authorization: localStorage.Authorization || '',
      uploadUrl: config.apiHost + '/web/sys/file/upload',
      previewVisible: false,
      previewImage: '',
    };
  },
  computed: {
    isEdit() {
      return Object.keys(this.default).length > 0;
    },
  },
  watch: {
    visible(val) {
      if (val) {
        if (this.isEdit) {
          this.form = JSON.parse(JSON.stringify(this.default));
          if (this.form.logo) {
            this.fileList = [
              {
                uid: '-1',
                name: 'image.png',
                status: 'done',
                url: this.form.logo,
              },
            ];
          }
        }
      } else {
        // this.handleModalCancel();
      }
    },
  },
  methods: {
    getBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = (error) => reject(error);
      });
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await this.getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    handleChange({ file, fileList }) {
      this.fileList = fileList;
    },
    handleModalConfirm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.modalLoading = true;
          const params = { ...this.form };
          params.leadNotice = params.leadNotice ? 1 : 0;
          params.logo = this.fileList?.[0]?.response?.data || this.fileList?.[0]?.url || '';
          if (this.isEdit) {
            delete params.coin;
          }
          const ajaxName = this.isEdit ? 'editApiList' : 'addApiList';
          const message = this.isEdit ? '编辑成功' : '新增成功';
          Ajax[ajaxName](params)
            .then(({ success }) => {
              if (success) {
                this.$message.success(message);
                this.$emit('success');
                this.handleModalCancel();
              }
            })
            .finally(() => {
              this.modalLoading = false;
            });
        }
      });
    },
    handleModalCancel() {
      this.fileList = [];
      this.form = this.$options.data().form;
      this.$refs.form.resetFields();
      this.$emit('close');
    },
  },
};
</script>

<style lang="scss" scoped>
.table-wrap {
  margin-top: 20px;
  padding-top: 16px;
}

.btn-gruop {
  display: flex;
  justify-content: flex-end;
}

::v-deep .ant-form-item {
  &:last-child {
    margin-bottom: 0;
  }
}
</style>
